package com.siashan.toolkit.ip.parser;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

import java.lang.reflect.Method;
import java.net.URL;

/**
 * ip地址解析工具类
 *
 * @author siashan
 * @since v1.0.4
 */
public class IpParser {
    public static String parse(String ip){
        //db
        String dbName = "ip2region.db";

        URL url = IpParser.class.getClassLoader().getResource(dbName);
        String path = url.getPath();
        //查询算法//B-tree
        int algorithm = DbSearcher.BTREE_ALGORITHM;
        try {
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, path);
            //define the method
            Method method = null;
            switch ( algorithm )
            {
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }
            DataBlock dataBlock = null;
            if (Util.isIpAddress(ip) == false ) {
            }
            dataBlock  = (DataBlock) method.invoke(searcher, ip);

            return fitAddr(dataBlock.getRegion());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private static String fitAddr(String ipAddr){
        String[] split = ipAddr.split("\\|");

        String country = "0".equals(split[0]) ? "" : split[0];
        String province = "0".equals(split[2]) ? "":split[2];
        String city = "0".equals(split[3]) ? "": split[3];
        StringBuilder sb = new StringBuilder();
        sb.append(country).append(" ").append(province).append(" ").append(city);
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(parse("171.15.165.80"));
        System.out.println(parse("192.168.1.1"));
        System.out.println(parse("171.15.165.80"));
        System.out.println(parse("171.15.165.80"));
        System.out.println(parse("169.235.24.133"));
    }
}
